package com.initapp.webapis.pownce
{
	import com.initapp.webapis.pownce.codes.PhotoType;
	import com.initapp.webapis.pownce.codes.SendToType;
	import com.initapp.webapis.pownce.objects.PownceApp;
	import com.initapp.webapis.pownce.objects.PownceEvent;
	import com.initapp.webapis.pownce.objects.PownceFile;
	import com.initapp.webapis.pownce.objects.PownceLink;
	import com.initapp.webapis.pownce.objects.PownceMedia;
	import com.initapp.webapis.pownce.objects.PownceNote;
	import com.initapp.webapis.pownce.objects.PownceReply;
	import com.initapp.webapis.pownce.objects.PownceSendOption;
	import com.initapp.webapis.pownce.objects.PownceUser;
	import com.initapp.webapis.pownce.results.PownceAuthResult;
	import com.initapp.webapis.pownce.results.PownceNotesResult;
	import com.initapp.webapis.pownce.results.PownceResult;
	import com.initapp.webapis.pownce.results.PownceSendOptionsResult;
	import com.initapp.webapis.pownce.results.PownceUsersResult;
	
	import flash.utils.Dictionary;
	
	use namespace pownce_internal;
		
	public final class PownceResultParser
	{
		pownce_internal static function parseAuth(authXML:XML):PownceAuthResult{
			var pownceAuthResult:PownceAuthResult = new PownceAuthResult();
			
			parseStandardFields(authXML, pownceAuthResult);
			
			if(pownceAuthResult.success){
				var pownceApp:PownceApp = new PownceApp();
				
				pownceApp.url = authXML.app.url;
				pownceApp.name = authXML.app.name;
				pownceApp.key = authXML.app.key;
				
				pownceAuthResult.username = authXML.username;
				pownceAuthResult.app = pownceApp;	
			}
			
			return pownceAuthResult;			
		}
		pownce_internal static function parseNotes(resultData:XML):PownceNotesResult{
			var pownceNotesResult:PownceNotesResult = new PownceNotesResult();
			var notes:Array = new Array();
			
			parseStandardFields(resultData, pownceNotesResult);
			
			if(pownceNotesResult.success){
				for each(var noteXML:XML in resultData.children()){
					var note:PownceNote = parsePownceNote(noteXML);
					
					notes.push(note);	
				}
				pownceNotesResult.notes = notes;
			}
			
			return pownceNotesResult;
		}
		pownce_internal static function parseNote(noteXML:XML):PownceNotesResult{
			var pownceNotesResult:PownceNotesResult = new PownceNotesResult();
			var notes:Array = new Array();
			
			parseStandardFields(noteXML, pownceNotesResult);
			
			if(pownceNotesResult.success){
				var note:PownceNote = parsePownceNote(noteXML);
					
				notes.push(note);
				pownceNotesResult.notes = notes;
			}
			
			return pownceNotesResult;			
		}
		pownce_internal static function parseSendToOptions(resultData:XML):PownceSendOptionsResult{
			var pownceSendToResult:PownceSendOptionsResult = new PownceSendOptionsResult();
			var sendOptions:Array = new Array();
			var sendOption:PownceSendOption;
			
			parseStandardFields(resultData, pownceSendToResult);
			
			if(pownceSendToResult.success){
				for each(var optionXML:XML in resultData.options.children()){

					switch (optionXML.name().toString()){
						case SendToType.ALL :
							sendOption = new PownceSendOption();
							
							sendOption.id = optionXML.name().toString();
							sendOption.name = optionXML[0].toString();	
							sendOption.type = SendToType.ALL;
							
							sendOptions.push(sendOption);
							break;
						case SendToType.SET :
							for each(var setXML:XML in optionXML.children()){
								sendOption = new PownceSendOption();
								
								sendOption.id = setXML.name().toString();
								sendOption.name = setXML[0].toString();
								sendOption.detailID = Number(setXML.name().toString().replace("set_", ""));
								sendOption.type = SendToType.SET;
								
								sendOptions.push(sendOption);
							}
							break;
						case SendToType.PRIVATE :
							for each(var privateXML:XML in optionXML.children()){
								sendOption = new PownceSendOption();
								
								sendOption.id = privateXML.name().toString();
								sendOption.name = privateXML[0].toString();
								sendOption.detailID = Number(privateXML.name().toString().replace("friend_", ""));
								sendOption.type = SendToType.SET;
								
								sendOptions.push(sendOption);
							}						
							break;
						case SendToType.PUBLIC :
							sendOption = new PownceSendOption();
							
							sendOption.id = optionXML.name().toString();
							sendOption.name = optionXML[0].toString();	
							sendOption.type = SendToType.PUBLIC;
							
							sendOptions.push(sendOption);						
							break;
					}
						
				}
				pownceSendToResult.options = sendOptions;
				pownceSendToResult.selected = resultData.selected;
			}
			
			return pownceSendToResult;
		}
		pownce_internal static function parseProfile(profileXML:XML):PownceUsersResult{
			var pownceUserResult:PownceUsersResult = new PownceUsersResult();
			var users:Array = new Array();

			parseStandardFields(profileXML, pownceUserResult);
			
			if(pownceUserResult.success){
				users.push(parsePownceUser(profileXML));
				pownceUserResult.totalCount = 1;
				pownceUserResult.hasNextPage = false;
				pownceUserResult.hasPrevPage = false;				
				pownceUserResult.users = users;
			}	
			
			return pownceUserResult;						
		}
		pownce_internal static function parseUserList(recipientListXML:XML):PownceUsersResult{
			var recipientListResult:PownceUsersResult = new PownceUsersResult();
			var users:Array = new Array();
			
			parseStandardFields(recipientListXML, recipientListResult);
			
			if(recipientListResult.success){
				recipientListResult.totalCount = Number(recipientListXML.total_count);
				recipientListResult.hasPrevPage = String(recipientListXML.has_prev_page) == "True" ? true : false;
				recipientListResult.hasNextPage = String(recipientListXML.has_next_page) == "True" ? true : false;
				for each(var userXML:XML in recipientListXML.users.children()){
					users.push(parsePownceUser(userXML));
				}
				users.length > 0 ? recipientListResult.users = users : null;
			}
			
			return recipientListResult;			
			
		}
		internal static function parsePownceNote(noteXML:XML):PownceNote{
			var note:PownceNote  = new PownceNote();
			var recipients:Array = new Array();
			var replies:Array = new Array();
			
			note.body = String(noteXML.body);
			note.permalink = String(noteXML.permalink);
			note.sender = parsePownceUser(XML(noteXML.sender.user));
			note.numReplies = Number(noteXML.num_replies);
			note.displaySince = String(noteXML.display_since);
			note.timestamp = Number(noteXML.timestamp);
			for each(var userXML:XML in noteXML.recipients.children()){
				recipients.push(parsePownceUser(userXML));
			}
			recipients.length > 0 ? note.recipients = recipients : null;
			note.secondsSince = Number(noteXML.seconds_since);
			note.numRecipients = Number(noteXML.num_recipients);
			note.linkURL = noteXML.link.url.hasSimpleContent() ? String(noteXML.link.url):"";
			
			if(noteXML.link.hasComplexContent()){
				var pownceLink:PownceLink = new PownceLink();
				
				pownceLink.url = noteXML.link.url.hasSimpleContent() ? String(noteXML.link.url) : "";
				if(noteXML.link.media.hasComplexContent()){
					var pownceMedia:PownceMedia = new PownceMedia();
					
					pownceMedia.src = noteXML.link.media.src.hasSimpleContent() ? String(noteXML.link.media.src) : "";
					pownceMedia.type = noteXML.link.media.type.hasSimpleContent() ? String(noteXML.link.media.type) : "";
					
					pownceLink.media = pownceMedia;	
				}
				note.link = pownceLink;
			}
			if(noteXML.file.hasComplexContent()){
				var pownceFile:PownceFile = new PownceFile();
				
				pownceFile.name = String(noteXML.file.name);
				pownceFile.type = String(noteXML.file.type);
				pownceFile.contentType = String(noteXML.file.content_type);
				pownceFile.awsURL = String(noteXML.file.aws_url);
				pownceFile.url = String(noteXML.file.url);
				
				note.file = pownceFile;
			}
			note.event = String(noteXML.event) != "" ? parsePownceEvent(XML(noteXML.event)):null;
			note.stars = Number(noteXML.stars);
			for each(var replyXML:XML in noteXML.replies.children()){
				replies.push(parsePownceReply(replyXML));
			}
			replies.length > 0 ? note.replies = replies : null;
			note.isPublic = noteXML.is_public == "True" ? true:false;
			note.id = Number(noteXML.id);
			note.isPrivate = noteXML.is_private == "True" ? true:false;
			note.type = noteXML.type;
			
			return note;
		}
		internal static function parsePownceReply(replyXML:XML):PownceReply{
			var reply:PownceReply = new PownceReply();
			var recipients:Array = new Array();
			var replies:Array = new Array();
			
			reply.body = String(replyXML.body);
			reply.sender = parsePownceUser(XML(replyXML.sender.user));
			reply.displaySince = String(replyXML.display_since);
			reply.timestamp = Number(replyXML.timestamp);

			reply.secondsSince = Number(replyXML.seconds_since);
			reply.id = Number(replyXML.id);
			reply.replyTo = Number(replyXML.reply_to);
			
			return reply;
		}
		internal static function parsePownceUser(userXML:XML):PownceUser{
			var user:PownceUser = new PownceUser();
			var userPhotos:Dictionary = new Dictionary();
			
			user.username = String(userXML.username);
			user.friendCount = Number(userXML.friend_count);
			user.permalink = String(userXML.permalink);
			user.fanCount = Number(userXML.fan_count);
			user.shortName = String(userXML.short_name);
			user.country = String(userXML.country);
			user.firstName = String(userXML.first_name);
			user.maxUploadMB = Number(userXML.max_upload_mb);
			
			userPhotos[PhotoType.SMEDIUM] = String(userXML.profile_photo_urls[PhotoType.SMEDIUM]);
			userPhotos[PhotoType.SMALL] = String(userXML.profile_photo_urls[PhotoType.SMALL]);
			userPhotos[PhotoType.TINY] = String(userXML.profile_photo_urls[PhotoType.TINY]);
			userPhotos[PhotoType.MEDIUM] = String(userXML.profile_photo_urls[PhotoType.MEDIUM]);
			userPhotos[PhotoType.LARGE] = String(userXML.profile_photo_urls[PhotoType.LARGE]);
			
			user.profilePhotoURLs = userPhotos;
			user.blurb = String(userXML.blurb);
			user.gender = String(userXML.gender);
			user.fanOfCount = Number(userXML.fan_of_count);
			user.isPro = userXML.is_pro == "True" ? true:false;
			user.location = String(userXML.location);
			
			return user;
		}
		internal static function parsePownceEvent(eventXML:XML):PownceEvent{
			var pownceEvent:PownceEvent = new PownceEvent();
			
			pownceEvent.name = eventXML.name;
			pownceEvent.location = eventXML.location;
			pownceEvent.date = parsePownceDate(eventXML.date);
			pownceEvent.googleMapURL = eventXML.google_map_url;
			pownceEvent.yahooMapURL = eventXML.yahoo_map_url;
			pownceEvent.ical = eventXML.ical;
			
			return pownceEvent;
		}
		internal static function parsePownceDate(val:String):Date{
			var dateArray:Array = String(val).substr(0,10).split("-");
			var timeArray:Array = String(val).substr(11,19).split(":")
			var date:Date = new Date(Number(dateArray[0]), Number(dateArray[1])-1, Number(dateArray[2]), Number(timeArray[0]), Number(timeArray[1]), Number(timeArray[2]));
			
			return date;
		}
		pownce_internal static function parseDateForPownce(date:Date):String{
			//2008-01-16 20:00
			var dateString:String;
			var month:String = date.month.toString().length == 1 ? "0" + date.month.toString() : date.month.toString();
			var day:String = date.date.toString().length == 1 ? "0" + date.date.toString(): date.date.toString();
			var hours:String = date.hours.toString().length == 1 ? "0" + date.hours.toString(): date.hours.toString();
			var minutes:String = date.minutes.toString().length == 1 ? "0" + date.minutes.toString(): date.minutes.toString();
			
			dateString = date.fullYear + "-" + month + "-" + day + " " + hours + ":" + minutes;
			
			return dateString;
		}
		internal static function parseStandardFields(resultData:XML, pownceResult:PownceResult):void{
			pownceResult.success = true;

			if(String(resultData.status_code) != ""){
				pownceResult.success = false;
				pownceResult.statusCode = resultData.status_code;
				pownceResult.message = resultData.message;
				pownceResult.request = resultData.request;
			}
			
		}
	}
}